package initializer

import (
	en2 "github.com/go-playground/locales/en"
	zh2 "github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
	"sgo/scontext"
	"sgo/svalidator"
	"strings"
)

type ValidatorInitializer struct{}

// 初始化数据校验

func (ValidatorInitializer) initialize(sc *scontext.SgoContext) error {
	sc.Validator = new(scontext.Validator)
	sc.Validator.Validate = validator.New()
	en := en2.New()
	zh := zh2.New()
	sc.Validator.Uni = ut.New(en, zh)
	tran, _ := sc.Validator.Uni.GetTranslator("zh")

	sc.Validator.Trans = &tran
	err := zh_translations.RegisterDefaultTranslations(sc.Validator.Validate, tran)
	if err != nil {
		return err
	}
	// 修改返回显示的字段名称使用tag->json
	sc.Validator.Validate.RegisterTagNameFunc(func(field reflect.StructField) string {
		name := strings.SplitN(field.Tag.Get("json"), ",", 2)[0]
		if name == "-" {
			return ""
		}
		return name
	})

	err = svalidator.Use(sc)
	if err != nil {
		return err
	}
	return nil
}
